#include <cstddef>
#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
#if defined(Q_WS_SIMULATOR)
#include <QNetworkProxy>
#endif
#include <QUrl>
#include <QtDeclarative>
#include <QSplashScreen>
#include <QPixmap>
#include <QTranslator>
#include <QLocale>
#include "qplatformdefs.h"

#include "networkaccessmanagerfactory.h"
#include "useragentprovider.h"
#include "setting.h"
#include <QtDebug>
#include <QFile>
#include <QTextStream>

void customMessageHandler(QtMsgType type, const char *msg)
{
    QString txt;
    switch (type) {
    case QtDebugMsg:
        txt = QString("Debug: %1").arg(msg);
        break;

    case QtWarningMsg:
        txt = QString("Warning: %1").arg(msg);
    break;
    case QtCriticalMsg:
        txt = QString("Critical: %1").arg(msg);
    break;
    case QtFatalMsg:
        txt = QString("Fatal: %1").arg(msg);
        abort();
    }
#ifdef MEEGO_EDITION_HARMATTAN
    QFile outFile("/opt/gNewsReader/qml/gNewsReader/debug.log");
#else
    QFile outFile("E://logs//gnewsreader//debug.log");
#endif
    outFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
    QTextStream ts(&outFile);
    ts << txt << endl;
}

Q_DECL_EXPORT int main(int argc, char *argv[])
{
    QScopedPointer<QApplication> app(createApplication(argc, argv));
    QLocale locale = QLocale::system();
    //QLocale locale = QLocale(QLocale::Italian, QLocale::China);
    QString localeString = locale.name();
    qDebug() << "Application Locale :" <<localeString;

//    qDebug() << "Font Path:" << QUrl::fromLocalFile("qml/gNewsReader/fonts/NokiaPureTextReg.ttf").toLocalFile();
//    QFontDatabase::addApplicationFont(QUrl::fromLocalFile("qml/gNewsReader/fonts/NokiaPureTextReg.ttf").toLocalFile());
//    QApplication::setFont(QFont("Nokia Pure Text"));

    app->setApplicationName(QString("gNewsReader")); //For Ovi Store
    app->setApplicationVersion(QString(APP_VERSION));

#if defined(Q_WS_SIMULATOR)
    QUrl proxyUrl(qgetenv("http_proxy"));
    if (proxyUrl.isValid() && !proxyUrl.host().isEmpty()) {
        int proxyPort = (proxyUrl.port() > 0) ? proxyUrl.port() : 8080;
        QNetworkProxy proxy(QNetworkProxy::HttpProxy, proxyUrl.host(), proxyPort);
        QNetworkProxy::setApplicationProxy(proxy);
    }
    else {
        QNetworkProxyQuery query(QUrl(QLatin1String("https://www.google.com")));
        QNetworkProxy proxy = QNetworkProxyFactory::systemProxyForQuery(query).value(0);
        if (proxy.type() != QNetworkProxy::NoProxy)
            QNetworkProxy::setApplicationProxy(proxy);
    }
#endif
    QPixmap pixmap("qml/gNewsReader/pics/splash.png");
    QSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint);
    splash.show();
    app->processEvents();
    splash.raise();
    app->processEvents();
    QmlApplicationViewer viewer;
    // Set custom NetworkAccessManagerFactory object in QDeclarative context
    UserAgentProvider p;
    QString userAgent = p.getUserAgent();

//#ifdef Q_OS_SYMBIAN
//    QDeclarativeEngine engine;
//    qDebug() << "Offline Storage Path: " << engine.offlineStoragePath();
//    engine.setOfflineStoragePath("E:\\Private\\20049f95\\QML\\OfflineStorage");
//    qDebug() << "Offline Storage Path: " << engine.offlineStoragePath();
//#endif

    NetworkAccessManagerFactory factory(userAgent);
    viewer.engine()->setNetworkAccessManagerFactory(&factory);

    qDebug() << QApplication::applicationDirPath();
#ifdef MEEGO_EDITION_HARMATTAN
    QWebSettings::globalSettings()->setUserStyleSheetUrl(QUrl::fromLocalFile("/opt/gNewsReader/qml/gNewsReader/css/addBlock.css"));
#else
    QWebSettings::globalSettings()->setUserStyleSheetUrl(QUrl::fromLocalFile("qml/gNewsReader/css/addBlock.css"));
#endif
    QWebSettings::globalSettings()->enablePersistentStorage();
    QWebSettings::globalSettings()->setAttribute(QWebSettings::TiledBackingStoreEnabled, true);
    QWebSettings::globalSettings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, true);
    app->processEvents();

    //Set platformStype for MeeGo
//    #if defined(Q_OS_SYMBIAN) || defined(Q_WS_SIMULATOR)
//        qDebug() << "Symbian UI platform style - Use default";
    #ifdef MEEGO_EDITION_HARMATTAN
        qDebug() << "MeeGo UI platform style";
        QScopedPointer<QDeclarativePropertyMap> platformStyle(new QDeclarativePropertyMap());
        platformStyle->insert("borderSizeMedium", QVariant(8));
        platformStyle->insert("paddingSmall", QVariant(4));
        platformStyle->insert("paddingMedium", QVariant(8));
        platformStyle->insert("paddingLarge", QVariant(12));
        platformStyle->insert("fontSizeSmall", QVariant(18));
        platformStyle->insert("colorNormalLight", QVariant(QColor(255, 255, 255)));
        platformStyle->insert("colorNormalDark", QVariant(QColor(0, 0, 0)));
        platformStyle->insert("colorNormalMid", QVariant(QColor(153, 153, 153)));
        platformStyle->insert("colorNormalLink", QVariant(QColor(0, 0, 200)));
        platformStyle->insert("colorNormalLightInverted", QVariant(QColor("#191919")));
        platformStyle->insert("colorNormalMidInverted", QVariant(QColor("#a6a8ab")));

        platformStyle->insert("fontFamilyRegular", QVariant(QString("Nokia Pure Text")));
        platformStyle->insert("fontFamilyLight", QVariant(QString("Nokia Pure Text")));
        platformStyle->insert("fontSizeMedium", QVariant(22));

        platformStyle->insert("fontSizeLarge", QVariant(26));
        platformStyle->insert("graphicSizeLarge", QVariant(48));
        platformStyle->insert("graphicSizeMedium", QVariant(32));
        platformStyle->insert("graphicSizeSmall", QVariant(24));
        platformStyle->insert("graphicSizeTiny", QVariant(20));

        viewer.rootContext()->setContextProperty("meegoStyle", platformStyle.data());
        //qmlRegisterType<FileIO, 1>("FileIO", 1, 0, "FileIO");

    #endif
    //qmlRegisterType<MyWebView>("myLib", 1, 0, "MyWebView");

    //Lets register our custom handler, before we start
    //qInstallMsgHandler(customMessageHandler);

    //Register custom URL handler to make pocket Auth scheme happy
    //QDesktopServices::setUrlHandler(QLatin1String("gnewsreader"), this, "handleBrowserCallback");

    Helper launcher;// = new Helper();
    viewer.rootContext()->setContextProperty("appLauncher", &launcher);
    viewer.rootContext()->setContextProperty("appVersion", QVariant(QString(APP_VERSION)));

    Settings settings("gNewsReader", "mainSettings");
    viewer.rootContext()->setContextProperty("settings", &settings);
    bool forceEnglish = settings.getValue("main/language/forceenglish", QVariant(QBool(false))).toBool();
//    SubItemModel subItemModel;
//    SubItemFilter subItemFilter;
//    subItemFilter.setSourceModel(&subItemModel);
//    viewer.rootContext()->setContextProperty("subListModel2", &subItemModel);
//    viewer.rootContext()->setContextProperty("subListModelFilter", &subItemFilter);

    //Load translations from qrc file
    qDebug() << "Application Country :" <<locale.country();
    qDebug() << "Application Country :" <<locale.countryToString(locale.country());
    if((locale.country() == QLocale::Taiwan || locale.country() == QLocale::Macau || locale.country() == QLocale::HongKong) && (locale.language() == QLocale::Chinese) )
        localeString = "zh_TW";
    if(forceEnglish) localeString = "en_US";
    qDebug() << "Application Locale :" <<localeString;
    QTranslator translator;
    if (translator.load("gtrans_" + localeString, ":/"))
            app->installTranslator(&translator);

#if defined(Q_OS_SYMBIAN) || defined(Q_WS_SIMULATOR)
    viewer.rootContext()->setContextProperty("applicationPlatform", QVariant(QString("symbian")));
    viewer.setMainQmlFile(QLatin1String("qml/gNewsReader/qml/newsreader.qml"));
#else
    viewer.rootContext()->setContextProperty("applicationPlatform", QVariant(QString("meego")));
    viewer.setMainQmlFile(QLatin1String("qml/gNewsReader/meego/newsreader.qml"));
#endif
    viewer.setAttribute(Qt::WA_OpaquePaintEvent);
    viewer.setAttribute(Qt::WA_NoSystemBackground);
    viewer.viewport()->setAttribute(Qt::WA_OpaquePaintEvent);
    viewer.viewport()->setAttribute(Qt::WA_NoSystemBackground);

    viewer.showExpanded();
    splash.finish(&viewer);

    QApplication::setAttribute(Qt::AA_S60DisablePartialScreenInputMode, false);
    return app->exec();

#ifdef Q_OS_SYMBIAN
    if(&pixmap != NULL) delete &pixmap;
    if(&splash != NULL) delete &splash;
#endif
}
